package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsBrand;
import com.qf.pojo.DtsCategory;
import com.qf.service.DtsCategoryService;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanghaotian
 * time:2022/12/21,0021 15:19
 * description:
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/admin/category")
public class CategoryController {

    @Autowired
    private DtsCategoryService categoryService;

    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(value = "limit",required = false,defaultValue = "20") Integer limit,
            String id,String name,String sort,String order
    ){
        IPage<DtsCategory> iPage = categoryService.findPage(page,limit,id,name,sort,order);
        Map<String,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());
        return ResponseUtil.ok(data);
    }

    @GetMapping("/l1")
    public Object l1(){
        List<CatVo> list = categoryService.findL1List();
        return ResponseUtil.ok(list);
    }

    @PostMapping("/create")
    public Object create(@RequestBody DtsCategory category){
        DtsCategory dtsCategory = null;
        try {
            dtsCategory = categoryService.insert(category);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,e.getMessage());
        }
        return ResponseUtil.ok(dtsCategory);
    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsCategory category){
        try {
            categoryService.update(category);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,e.getMessage());
        }
        return ResponseUtil.ok();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsCategory category){
        try {
            categoryService.delete(category);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,e.getMessage());
        }
        return ResponseUtil.ok();
    }
}
